import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import NotFound from '../views/NotFound.vue'
import store from '@/store/index.js'
Vue.use(VueRouter)
const one = {
	path: '/menu/one',
	component: () => import('@/views/Page1.vue')
}
const two = {
	path: '/menu/two',
	component: () => import('@/views/Page1.vue')
}
const three = {
	path: '/menu/three',
	component: () => import('@/views/Page1.vue')
}
const four = {
	path: '/menu/four',
	component: () => import('@/views/Page1.vue')
}
const five = {
	path: '/menu/five',
	component: () => import('@/views/Page1.vue')
}
const ruleMapping = {
	'/menu/one': one,
	'/menu/two': two,
	'/menu/three': three,
	'/menu/four': four,
	'/menu/five': five
}
const routes = [{
		path: '/',
		name: 'Home',
		component: Home,
		redirect: '/menu/one',
		children: [
			//动态路由
		]
	},
	{
		path: '/about',
		name: 'About',
		// route level code-splitting
		// this generates a separate chunk (about.[hash].js) for this route
		// which is lazy-loaded when the route is visited.
		component: () => import( /* webpackChunkName: "about" */ '../views/About.vue')
	},
	{
		path: '/login',
		name: 'Login',
		// route level code-splitting
		// this generates a separate chunk (about.[hash].js) for this route
		// which is lazy-loaded when the route is visited.
		component: () => import( /* webpackChunkName: "about" */ '../views/Login.vue')
	},
	{
		path: '*',
		name: 'NotFound',
		component: NotFound
	}

]

const router = new VueRouter({
	routes
})
router.beforeEach((to, from, next) => {
	if (to.path == '/login') {
		next()
	} else {
		let token = window.sessionStorage.getItem('token')
		if (!token) {
			next('/login')
		} else {
			next()
		}
	}
})
export function initDynamicRoutes() {
	/* console.log(router); */
	const rulerouter = router.options.routes
	/* console.log(rulerouter); */
	const rightlist = store.state.user.rights
	if (rightlist) {
		rightlist.forEach(v => {
			if (v.children) {
				v.children.forEach(item => {
					console.log(item); 
					if (item.path) {
						const temp = ruleMapping[item.path]
						temp.meta = item.rights
						rulerouter[0].children.push(temp)
						/* rulerouter[0].children.forEach(v=>{
							router.addRoute('Home',v)
						}) */
					}
				})
			}
		})
	}
	router.addRoutes(rulerouter)
}


const originalPush = VueRouter.prototype.push
// 重写了原型上的push方法，统一的处理了错误信息
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}
export default router
